package com.codeckz.library_face.ui

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.ViewTreeObserver
import android.view.WindowManager
import android.widget.RelativeLayout
import androidx.annotation.RequiresApi
import androidx.camera.view.CameraController
import com.codeckz.library_face.FaceGetOptions
import com.codeckz.library_face.FaceGetterPlugins
import com.codeckz.library_face.R
import com.codeckz.library_face.controller.Camera19Controller
import com.codeckz.library_face.controller.CameraxController
import com.codeckz.library_face.controller.ICameraController
import com.codeckz.library_face.databinding.ActivityFaceGetter19Binding
import com.codeckz.library_face.databinding.ActivityFaceGetterBinding
import com.codeckz.library_face.utils.BrightnessTools
import com.codeckz.library_face.widget.WaveHelper
import com.codeckz.library_face.widget.WaveView

/**
 *@packageName com.codeckz.library_face.ui
 *@author kzcai
 *@date 2022/1/18
 */
class FaceGetter19Activity : BaseActivity<ActivityFaceGetter19Binding>() {


    companion object {
        fun openFacePage(context: Context, options: FaceGetOptions) {
            val intent = Intent(context, FaceGetter19Activity::class.java)
            intent.putExtra("options", options)
            context.startActivity(intent)
        }
    }

    private lateinit var controller: ICameraController
    private var cameraFacing: Int = 0
    private lateinit var options:FaceGetOptions

    private var mWaveview: WaveView? = null
    private var mWaveHelper: WaveHelper? = null


    override fun initContentView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_face_getter_19
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        options = intent.getSerializableExtra("options") as FaceGetOptions
        cameraFacing = options.cameraFaceing
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
        }
        if (Build.VERSION.SDK_INT >= 28) {
            val lp = window.attributes
            lp.layoutInDisplayCutoutMode =
                WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
            window.attributes = lp
        }
        super.onCreate(savedInstanceState)
        controller = Camera19Controller(context)
        controller.filterFace = options.faceFilter
        initView()
        initController()


    }

    private fun initController() {
        controller.cameraFacing =
            cameraFacing
        controller.setPreviewView(binding.previewFinder)
        Handler(Looper.myLooper()!!).postDelayed({
            val rect = binding.faceView.faceCircleRect
            controller.circleRect = rect
            initWaveView(binding.faceView.faceRoundRect)
            initSuccessImg()
            controller.startCamera()
        }, 100)

        controller.onImageAnalysisListener = { image, result ->

            runOnUiThread {
                if (result.success) {
                    num++
                    binding.tvResult.text = ""
                    showProgressBar(true)
                    if (!isFinishing && num > 3) {
                        binding.successImage.visibility = View.VISIBLE
                        Handler(Looper.myLooper()!!).postDelayed({
                            FaceGetterPlugins.sendImageData(image!!)
                            finish()
                        }, 400)
                    }
                } else {
                    num = 0
                    binding.tvResult.text = result.errorStr
                    showProgressBar(false)
                    binding.successImage.visibility = View.GONE
                }
            }
        }
    }

    private var num = 0

    private fun initView() {
        initBrightness()



        binding.btnSwitch.setOnClickListener {
            controller
                .switchCamera()
        }

        binding.ivClose.setOnClickListener {
            finish()
        }
    }

    private fun initSuccessImg() {
        val mSuccessView = binding.successImage
        mSuccessView.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                if (mSuccessView.tag == null) {
                    val rect: Rect = binding.faceView.faceRoundRect
                    val rlp = mSuccessView.layoutParams as RelativeLayout.LayoutParams
                    val w = resources.getDimension(R.dimen.success_width).toInt()
                    rlp.setMargins(
                        rect.centerX() - w / 2,
                        rect.top - w / 2,
                        0,
                        0
                    )
                    mSuccessView.layoutParams = rlp
                    mSuccessView.tag = "setlayout"
                }
                mSuccessView.visibility = View.GONE
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    mSuccessView.viewTreeObserver.removeGlobalOnLayoutListener(this)
                } else {
                    mSuccessView.viewTreeObserver.removeOnGlobalLayoutListener(this)
                }
            }
        })

    }

    private fun initWaveView(rect: Rect) {
        val rootView = binding.rlRoot
        val waveParams: RelativeLayout.LayoutParams = RelativeLayout.LayoutParams(
            rect.width(), rect.height()
        )
        waveParams.setMargins(rect.left, rect.top, rect.left, rect.top)
        waveParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE)
        waveParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE)
        mWaveview = WaveView(this);
        rootView.addView(mWaveview, waveParams);
        mWaveHelper = WaveHelper(mWaveview)

        mWaveview?.setShapeType(WaveView.ShapeType.CIRCLE)
        mWaveview?.setWaveColor(
            Color.parseColor("#28FFFFFF"),
            Color.parseColor("#3cFFFFFF")
        )

        val mBorderColor = Color.parseColor("#28f16d7a");
        mWaveview?.setBorder(0, mBorderColor);
    }

    private fun initBrightness() {
        val brightness = BrightnessTools.getScreenBrightness(this)
        if (brightness < 200) {
            BrightnessTools.setBrightness(this, 200)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        controller.release()
    }

    override fun onStop() {
        super.onStop()
        if (mWaveview != null) {
            mWaveview?.visibility = View.GONE
            mWaveHelper?.cancel()
        }
    }

    override fun onPause() {
        super.onPause()
        if (mWaveview != null) {
            mWaveHelper?.cancel()
            mWaveview?.visibility = View.GONE
        }
    }

    private fun showProgressBar(show: Boolean) {
        runOnUiThread {
            if (show) {
                if (mWaveview != null) {
                    mWaveview!!.visibility = View.VISIBLE
                    mWaveHelper!!.start()
                }
            } else {
                if (mWaveview != null) {
                    mWaveview!!.visibility = View.GONE
                    mWaveHelper!!.cancel()
                }
            }
        }
    }

}